/*
 * @Author: 梁青春
 * @Date: 2022-04-22 11:36:02
 * @LastEditTime: 2022-04-24 17:25:21
 * @LastEditors: 梁青春
 */
import { createStore } from 'vuex'
import { ElMessage } from 'element-plus'
import cloneDeep from 'lodash/cloneDeep'
import api from '@/api'

export default createStore({
  state: {
    userInfo: {
      id: '',
      account: '',
      name: '',
      headimg: '',
      phone: ''
    },
    specsFontSize: 1.25, //字体规格 常规1  中1.25  大1.5
    theme: 'light', // 主题
    isCollapse: false
  },
  mutations: {
    // 重置vuex本地储存状态
    resetStore (state) {
      Object.keys(state).forEach((key) => {
        state[key] = cloneDeep(window.SITE_CONFIG['storeState'][key])
      })
    },
    // 更新用户信息
    setUserInfo(state, data){
      state.userInfo = data;
    },
    // 更新字体规格
    updateSpecsFontSize(state, data){
      state.specsFontSize = data;
      document.documentElement.style.fontSize =  data * state.baseFontSize + 'px'
    },
    // 更新主题
    updateTheme(state, data) {
      state.theme = data;
    },
    updateIsCollapse(state, data) {
      state.isCollapse = data;
    }
  },
  actions: {
    userInfo({state,commit}){
			api.user.userInfo()
			.then(data=>{				
				commit('setUserInfo', data.user)
			})
		},
    login({state, commit, dispatch}, data) {
			return new Promise((resolve, reject) => {
				api.user.login(data).then(async (res) => {					
					if (res && res.code === 0) {
						if (res.user.userId) {
							await dispatch('userInfo')
						}
					} else {
						ElMessage.error(res.msg)
					}
					resolve(res)
				})
			}).catch(err => {
				reject(err)
			})
		}
  },
  strict: import.meta.env.NODE_ENV !== 'production'
})
